package Presentacion;

import Datos.Conexion;
import Logica.Pacientes;
import Logica.Usuarios;
import java.awt.HeadlessException;
import java.sql.*;
//import java.util.Date;
import java.text.SimpleDateFormat;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Administrator
 */
public class FrmPacientes extends javax.swing.JFrame {

    /**
     * Creates new form FrmPacientes
     */
    public FrmPacientes() {
        initComponents();
        //cargarIconoBackground();
        cargarPacientes("");
        cargarPacientest("");
        desactivar();
    }
    

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        opciones = new javax.swing.JPopupMenu();
        Editar = new javax.swing.JMenuItem();
        Eliminar = new javax.swing.JMenuItem();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtcedula = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtnombre = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txtapellido = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        txtcodigo = new javax.swing.JTextField();
        txttelefono = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        cmbsexo = new javax.swing.JComboBox();
        btnguardar = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        txtfiltro = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        btnbuscar = new javax.swing.JButton();
        btnlimpiar = new javax.swing.JButton();
        btnagregar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbvista = new javax.swing.JTable();
        btnsalir = new javax.swing.JButton();
        btnnuevo = new javax.swing.JButton();
        btncancelar = new javax.swing.JButton();
        jLabel10 = new javax.swing.JLabel();
        txtlocalidad = new javax.swing.JTextField();
        jLabel11 = new javax.swing.JLabel();
        txtnacionalidad = new javax.swing.JTextField();
        calendario = new com.toedter.calendar.JDateChooser();
        jLabel12 = new javax.swing.JLabel();
        cmbestado = new javax.swing.JComboBox();
        jLabel13 = new javax.swing.JLabel();
        txtusuario = new javax.swing.JTextField();
        jPanel2 = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        jLabel9 = new javax.swing.JLabel();
        txtfiltro1 = new javax.swing.JTextField();
        btnbuscar1 = new javax.swing.JButton();
        btnlimpiar1 = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        tbvista1 = new javax.swing.JTable();
        btnsalir1 = new javax.swing.JButton();

        opciones.setLabel("");
        opciones.setName(""); // NOI18N

        Editar.setText("Editar");
        Editar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                EditarActionPerformed(evt);
            }
        });
        opciones.add(Editar);

        Eliminar.setText("Eliminar");
        Eliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                EliminarActionPerformed(evt);
            }
        });
        opciones.add(Eliminar);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setOpaque(false);

        jLabel1.setText("Cod. de Pac.:");

        jLabel2.setText("Nombre:");

        jLabel3.setText("Apellido:");

        jLabel4.setText("Fecha. de Nac.:");

        jLabel5.setText("Cedula de Identidad:");

        txtcodigo.setEditable(false);
        txtcodigo.setEnabled(false);

        jLabel6.setText("Teléfono:");

        jLabel7.setText("SEXO:");

        cmbsexo.setEditable(true);
        cmbsexo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "[Seleccione SEXO]", "MASCULINO", "FEMENINO" }));

        btnguardar.setText("Guardar");
        btnguardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnguardarActionPerformed(evt);
            }
        });

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Registros de Pacientes"));
        jPanel3.setOpaque(false);

        txtfiltro.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtfiltroActionPerformed(evt);
            }
        });
        txtfiltro.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtfiltroKeyPressed(evt);
            }
        });

        jLabel8.setText("Nombre:");

        btnbuscar.setText("Buscar");
        btnbuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnbuscarActionPerformed(evt);
            }
        });

        btnlimpiar.setText("Limpiar");
        btnlimpiar.setEnabled(false);
        btnlimpiar.setOpaque(false);
        btnlimpiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnlimpiarActionPerformed(evt);
            }
        });

        btnagregar.setText("Agregar");

        tbvista.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        tbvista.setComponentPopupMenu(opciones);
        tbvista.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbvistaMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tbvista);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel8)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtfiltro, javax.swing.GroupLayout.PREFERRED_SIZE, 310, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 215, Short.MAX_VALUE)
                        .addComponent(btnbuscar)
                        .addGap(18, 18, 18)
                        .addComponent(btnlimpiar)
                        .addGap(18, 18, 18)
                        .addComponent(btnagregar)))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(txtfiltro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnlimpiar)
                    .addComponent(btnagregar)
                    .addComponent(btnbuscar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 106, Short.MAX_VALUE)
                .addContainerGap())
        );

        btnsalir.setText("Salir");
        btnsalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnsalirActionPerformed(evt);
            }
        });

        btnnuevo.setText("Nuevo");
        btnnuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnnuevoActionPerformed(evt);
            }
        });

        btncancelar.setText("Cancelar");

        jLabel10.setText("Localidad:");

        jLabel11.setText("Nacionalidad:");

        calendario.setDateFormatString("yyyy-MM-dd");

        jLabel12.setText("Estado:");

        cmbestado.setEditable(true);
        cmbestado.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "[Seleccione Estado]", "ACTIVO", "INACTIVO" }));

        jLabel13.setText("Usuario:");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(45, 45, 45)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel1)
                                    .addComponent(jLabel3)))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(jLabel5))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel12, javax.swing.GroupLayout.Alignment.TRAILING))))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txtcodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtapellido, javax.swing.GroupLayout.DEFAULT_SIZE, 396, Short.MAX_VALUE)
                            .addComponent(txtnombre)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(cmbestado, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGap(250, 250, 250))))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(81, 81, 81)
                        .addComponent(jLabel7)
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(txtcedula)
                            .addComponent(calendario, javax.swing.GroupLayout.DEFAULT_SIZE, 146, Short.MAX_VALUE)
                            .addComponent(cmbsexo, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                                .addGap(63, 63, 63)
                                .addComponent(jLabel6)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txttelefono, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                            .addComponent(jLabel13)
                                            .addComponent(jLabel11))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addGap(61, 61, 61)
                                        .addComponent(jLabel10)
                                        .addGap(6, 6, 6)))
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(txtlocalidad)
                                    .addComponent(txtnacionalidad, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE)
                                    .addComponent(txtusuario))))))
                .addContainerGap(334, Short.MAX_VALUE))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(btnnuevo, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btnguardar, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btncancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnsalir, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(29, 29, 29))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtcodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtnombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(14, 14, 14)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtapellido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(txttelefono, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtcedula, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(cmbsexo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtlocalidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel10))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel11)
                        .addComponent(txtnacionalidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel4))
                    .addComponent(calendario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel12)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(cmbestado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel13)
                        .addComponent(txtusuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 9, Short.MAX_VALUE)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnnuevo, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnguardar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btncancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnsalir, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        jTabbedPane1.addTab("Registro de Pacientes", jPanel1);

        jPanel2.setOpaque(false);

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Registros de Pacientes"));
        jPanel4.setOpaque(false);

        jLabel9.setText("Nombre:");

        txtfiltro1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtfiltro1KeyPressed(evt);
            }
        });

        btnbuscar1.setText("Buscar");
        btnbuscar1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnbuscar1ActionPerformed(evt);
            }
        });

        btnlimpiar1.setText("Limpiar");
        btnlimpiar1.setEnabled(false);
        btnlimpiar1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnlimpiar1ActionPerformed(evt);
            }
        });

        tbvista1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane2.setViewportView(tbvista1);

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGap(25, 25, 25)
                .addComponent(jLabel9)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(txtfiltro1, javax.swing.GroupLayout.PREFERRED_SIZE, 343, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(btnbuscar1)
                .addGap(39, 39, 39)
                .addComponent(btnlimpiar1)
                .addContainerGap(231, Short.MAX_VALUE))
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addComponent(jScrollPane2)
                .addContainerGap())
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel9)
                        .addComponent(txtfiltro1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(btnbuscar1, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(btnlimpiar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(101, 101, 101))
        );

        btnsalir1.setText("Salir");
        btnsalir1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnsalir1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(btnsalir1, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(24, 24, 24))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, 352, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 38, Short.MAX_VALUE)
                .addComponent(btnsalir1, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        jTabbedPane1.addTab("Cosulta de Pacientes", jPanel2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTabbedPane1)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTabbedPane1)
                .addContainerGap())
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void btnsalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnsalirActionPerformed
        // TODO add your handling code here:
        System.exit(0);
    }//GEN-LAST:event_btnsalirActionPerformed

    private void txtfiltroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtfiltroActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtfiltroActionPerformed

    private void txtfiltroKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtfiltroKeyPressed
        // TODO add your handling code here:
        cargarPacientes(txtfiltro.getText().trim());
        if (txtfiltro.getText().length() > 0) {
            btnlimpiar.setEnabled(true);
        } else {
            btnlimpiar.setEnabled(false);
        }
    }//GEN-LAST:event_txtfiltroKeyPressed

    private void txtfiltro1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtfiltro1KeyPressed
        // TODO add your handling code here:
        cargarPacientest(txtfiltro1.getText().trim());
        if (txtfiltro1.getText().length() > 0) {
            btnlimpiar1.setEnabled(true);
        } else {
            btnlimpiar1.setEnabled(false);
        }
    }//GEN-LAST:event_txtfiltro1KeyPressed

    private void btnsalir1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnsalir1ActionPerformed
        // TODO add your handling code here:
        System.exit(0);
    }//GEN-LAST:event_btnsalir1ActionPerformed

    private void btnbuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnbuscarActionPerformed
        // TODO add your handling code here:
        cargarPacientes(txtfiltro.getText().trim());
    }//GEN-LAST:event_btnbuscarActionPerformed

    private void btnbuscar1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnbuscar1ActionPerformed
        // TODO add your handling code here:
        cargarPacientes(txtfiltro1.getText().trim());
    }//GEN-LAST:event_btnbuscar1ActionPerformed

    private void btnlimpiar1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnlimpiar1ActionPerformed
        // TODO add your handling code here:
        txtfiltro1.setText("");
    }//GEN-LAST:event_btnlimpiar1ActionPerformed

    private void btnlimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnlimpiarActionPerformed
        // TODO add your handling code here:
        txtfiltro.setText("");
    }//GEN-LAST:event_btnlimpiarActionPerformed

    private void tbvistaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbvistaMouseClicked
        // TODO add your handling code here:
        int filasel = tbvista.getSelectedRow();
        String id = (String) modelo.getValueAt(filasel,0);
        asignarcampos(id);
    }//GEN-LAST:event_tbvistaMouseClicked

    private void btnguardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnguardarActionPerformed
        // TODO add your handling code here:
        Conexion sqlserver = new Conexion();
        Connection cnn = sqlserver.conectar();
        SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");
        
        Pacientes pacientes = new Pacientes();
        
        
        pacientes.setNombre(txtnombre.getText());
        pacientes.setApellidos(txtapellido.getText());
        pacientes.setCedula(txtcedula.getText());
        pacientes.setTelefono(txttelefono.getText());
        pacientes.setSexo(cmbsexo.getSelectedItem().toString());
        pacientes.setFecha_nacimiento(formato.format(calendario.getDate()));
        pacientes.setCod_usuario(Integer.parseInt(txtusuario.getText()));
        pacientes.setEstado(cmbestado.getSelectedItem().toString());
        
        pacientes.setCod_localidad(Integer.parseInt(txtlocalidad.getText()));
        pacientes.setCod_nacionalidad(Integer.parseInt(txtnacionalidad.getText()));
        
        
        String sql = "";
        String mensaje="";
        
        
        switch(accion) {
            case "Insertar":
                sql = " execute insertar_paciente " + " ?, ?, ?, ?, ?, ?, ?, ?, ?, ?";
                mensaje="Exitoso Registro";
            break;
            case "Editar":
            sql = " execute modificar_paciente " + id_actualizar + ", ?, ?, ?, ?, ?, ?, ?, ?, ?, ?";
            mensaje = "El paciente fue modificado satisfactoriamente";
            break;
          
        }
        try {
            PreparedStatement pst = cnn.prepareStatement(sql);
            pst.setString(1, pacientes.getNombre());
            pst.setString(2, pacientes.getApellidos());
            pst.setString(3, pacientes.getCedula());
            pst.setString(4, pacientes.getTelefono());
            pst.setString(5, pacientes.getSexo());
            pst.setString(6, pacientes.getFecha_nacimiento());               
            pst.setInt(7, pacientes.getCod_usuario());
            pst.setString(10, pacientes.getEstado());
            pst.setInt(8, pacientes.getCod_localidad());
            pst.setInt(9, pacientes.getCod_nacionalidad());
            


            
            int n = pst.executeUpdate();
            if (n > 0) {
                JOptionPane.showMessageDialog(null, mensaje);
                cargarPacientes("");
                cargarPacientest("");
            }
            cnn.close();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex);
        }
      limpiar();
      desactivar();
      btnagregar.setEnabled(true);
    }//GEN-LAST:event_btnguardarActionPerformed

    private void btnnuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnnuevoActionPerformed
        // TODO add your handling code here:
        limpiar();
        habilitar();
      
    }//GEN-LAST:event_btnnuevoActionPerformed

    private void EditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EditarActionPerformed
        // TODO add your handling code here:
        int filasel;
        String id;
        filasel = tbvista.getSelectedRow();              
        try {

            if (filasel == -1 ) {
                JOptionPane.showMessageDialog(null, "Favor seleccione una fila");
            } else {
               accion = "Editar"; 
               modelo = (DefaultTableModel) tbvista.getModel();
               id= (String) modelo.getValueAt(filasel,0);
               btnnuevo.setEnabled(false);
               habilitar();
               asignarcampos(id);
               id_actualizar = id;
            }
        } 
        catch (HeadlessException e) {
            JOptionPane.showMessageDialog(null, e);
        }  
    }//GEN-LAST:event_EditarActionPerformed

    private void EliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EliminarActionPerformed
        int ban = JOptionPane.showConfirmDialog(null, "Realmente desea eliminar el paciente?");
        if (ban == JOptionPane.YES_OPTION) {
            int filasel;
            String id;
            filasel = tbvista.getSelectedRow();
            try {

                if (filasel == -1) {
                    JOptionPane.showMessageDialog(null, "Favor seleccione una fila");
                } else {
                    modelo = (DefaultTableModel) tbvista.getModel();
                    id = (String) modelo.getValueAt(filasel, 0);
                    eliminar(Integer.parseInt(id));
                }

            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, e);
            }
         }
    }//GEN-LAST:event_EliminarActionPerformed

            public void eliminar (int id){
      	Conexion sqlserver = new Conexion();
      	Connection cnn = sqlserver.conectar();

        Usuarios objeto= new Usuarios();

        objeto.setCod_usuario(id);

        String sql = "DELETE FROM pacientes WHERE cod_paciente = ?";
        String mensaje = "El paciente fue eliminado correctamente";

        try {
            PreparedStatement pst = cnn.prepareStatement(sql);
            pst.setString(1, String.valueOf(objeto.getCod_usuario()));

            int n = pst.executeUpdate();
            if (n > 0) {
                JOptionPane.showMessageDialog(null, mensaje);
                cargarPacientes("");
            }
            cnn.close();
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, ex);
        }    
        limpiar();
    }
    
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FrmPacientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FrmPacientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FrmPacientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FrmPacientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FrmPacientes().setVisible(true);
            }
        });
    }
    DefaultTableModel modelo;
    String accion = "Insertar";
    private void cargarPacientes(String filtro){
        Conexion sqlserver = new Conexion();
        Connection cnn = sqlserver.conectar();
        String[] titulos = {"Código","Nombre","Apellido","Cédula","Tel.","Sexo","Fecha de Nac.","Fecha Creación","Fecha Edición","Usuario","Estado","Localidad","Nacionalidad"};
         modelo= new DefaultTableModel(null,titulos);
        String [] registro = new String[13];
        String sql ="Select * from pacientes where nombres LIKE '%" + filtro +"%' "; 
            try {
            Statement st = cnn.createStatement();
            ResultSet resultado = st.executeQuery(sql);
            while(resultado.next()){
                registro[0]=resultado.getString("cod_paciente");
                registro[1]=resultado.getString("nombres");
                registro[2]=resultado.getString("apellidos");
                registro[3]=resultado.getString("cedula");
                registro[4]=resultado.getString("telefono");
                registro[5]=resultado.getString("sexo");
                registro[6]=resultado.getString("fecha_nacimiento");
                registro[7]=resultado.getString("fecha_creacion");
                registro[8]=resultado.getString("fecha_ultima_edicion");
                registro[9]=resultado.getString("cod_usuario");
                registro[10]=resultado.getString("estado");
                registro[11]=resultado.getString("cod_localidad");
                registro[12]=resultado.getString("cod_nacionalidad");
                modelo.addRow(registro);
            }
            tbvista.setModel(modelo);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);
        }
    
    
    }
    private void cargarPacientest(String filtro1){
        Conexion sqlserver = new Conexion();
        Connection cnn;
        cnn = sqlserver.conectar();
        String[] titulos = {"Código","Nombre","Apellido","Cédula","Tel.","Sexo","Fecha de Nac.","Fecha Creación","Fecha Edición","Usuario","Estado","Localidad","Nacionalidad"};
        DefaultTableModel modelo= new DefaultTableModel(null,titulos);
        String [] registro = new String[13];
        String sql ="Select * from pacientes where nombres LIKE '%" + filtro1 +"%' ";
            try {
            Statement st = cnn.createStatement();
            ResultSet resultado = st.executeQuery(sql);
            while(resultado.next()){
                registro[0]=resultado.getString("cod_paciente");
                registro[1]=resultado.getString("nombres");
                registro[2]=resultado.getString("apellidos");
                registro[3]=resultado.getString("cedula");
                registro[4]=resultado.getString("telefono");
                registro[5]=resultado.getString("sexo");
                registro[6]=resultado.getString("fecha_nacimiento");
                registro[7]=resultado.getString("fecha_creacion");
                registro[8]=resultado.getString("fecha_ultima_edicion");
                registro[9]=resultado.getString("cod_usuario");
                registro[10]=resultado.getString("estado");
                registro[11]=resultado.getString("cod_localidad");
                registro[12]=resultado.getString("cod_nacionalidad");
                modelo.addRow(registro);
            }
            tbvista1.setModel(modelo);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);
        }
    
    
    }
     String id_actualizar ="";
     private void asignarcampos(String cod){
      Conexion sqlserver = new Conexion(); 
      Connection cnn = sqlserver.conectar();
      
      
      
      String sql = "SELECT * FROM pacientes where cod_paciente="+ cod;
      try 
      {
        Statement st = cnn.createStatement();
        ResultSet resultado = st.executeQuery(sql);
        if(resultado.next()){
                txtcodigo.setText(resultado.getString("cod_paciente"));
                txtnombre.setText(resultado.getString("nombres"));
                txtapellido.setText(resultado.getString("apellidos"));
                txtcedula.setText(resultado.getString("cedula"));
                txttelefono.setText(resultado.getString("telefono"));
                cmbsexo.setSelectedItem(resultado.getString("sexo"));
                
                calendario.setDate(resultado.getDate( "fecha_nacimiento"));
                //resultado.getString("fecha_nacimiento");
                
                txtusuario.setText(resultado.getString("cod_usuario"));
                cmbestado.setSelectedItem(resultado.getString("estado"));
                txtlocalidad.setText(resultado.getString("cod_localidad"));
                txtnacionalidad.setText(resultado.getString("cod_nacionalidad"));
                
          
        }
      } 
      catch (SQLException e) 
      {
            JOptionPane.showMessageDialog(null, e);
      }
      //id_actualizar = cod;
    } 
     private void cargarIconoBackground(){
        setIconImage(new ImageIcon(getClass().getResource("/Imagenes/tooth-button.png")).getImage());
        ((JPanel)getContentPane()).setOpaque(false);
        ImageIcon uno=new ImageIcon(this.getClass().getResource("/Imagenes/background.jpg"));
        JLabel fondo= new JLabel();
        fondo.setIcon(uno);
        getLayeredPane().add(fondo,JLayeredPane.FRAME_CONTENT_LAYER);
        fondo.setBounds(0,0,uno.getIconWidth(),uno.getIconHeight());
    }
      private void limpiar(){
        txtcodigo.setText("");
        txtnombre.setText("");
        txtapellido.setText("");
        txtcedula.setText("");
        cmbsexo.setSelectedIndex(0);
        cmbestado.setSelectedIndex(0);
        calendario.setDate(null);
        txttelefono.setText("");
        txtusuario.setText("");
        txtlocalidad.setText("");
        txtnacionalidad.setText("");
    }
     private void desactivar() {
         txtnombre.setEnabled(false);
         txtapellido.setEnabled(false);
         txtcedula.setEnabled(false);
         txtlocalidad.setEnabled(false);
         txttelefono.setEnabled(false);
         txtnacionalidad.setEnabled(false);
         calendario.setEnabled(false);
         cmbsexo.setEnabled(false);
         //btnguardar.setEnabled(false);
         btncancelar.setEnabled(false);
         cmbestado.setEnabled(false);
         txtusuario.setEnabled(false);
         
     }
     private void habilitar(){
                  txtnombre.setEnabled(true);
         txtapellido.setEnabled(true);
         txtcedula.setEnabled(true);
         txtlocalidad.setEnabled(true);
         txttelefono.setEnabled(true);
         txtnacionalidad.setEnabled(true);
         calendario.setEnabled(true);
         cmbsexo.setEnabled(true);
         //btnguardar.setEnabled(true);
         btncancelar.setEnabled(true);
         cmbestado.setEnabled(true);
         txtusuario.setEnabled(true);
        }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem Editar;
    private javax.swing.JMenuItem Eliminar;
    private javax.swing.JButton btnagregar;
    private javax.swing.JButton btnbuscar;
    private javax.swing.JButton btnbuscar1;
    private javax.swing.JButton btncancelar;
    private javax.swing.JButton btnguardar;
    private javax.swing.JButton btnlimpiar;
    private javax.swing.JButton btnlimpiar1;
    private javax.swing.JButton btnnuevo;
    private javax.swing.JButton btnsalir;
    private javax.swing.JButton btnsalir1;
    private com.toedter.calendar.JDateChooser calendario;
    private javax.swing.JComboBox cmbestado;
    private javax.swing.JComboBox cmbsexo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JPopupMenu opciones;
    private javax.swing.JTable tbvista;
    private javax.swing.JTable tbvista1;
    private javax.swing.JTextField txtapellido;
    private javax.swing.JTextField txtcedula;
    private javax.swing.JTextField txtcodigo;
    private javax.swing.JTextField txtfiltro;
    private javax.swing.JTextField txtfiltro1;
    private javax.swing.JTextField txtlocalidad;
    private javax.swing.JTextField txtnacionalidad;
    private javax.swing.JTextField txtnombre;
    private javax.swing.JTextField txttelefono;
    private javax.swing.JTextField txtusuario;
    // End of variables declaration//GEN-END:variables


    
}